<?php namespace Base;

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;
use PHPSocketIO\SocketIO;
use Predis\Client as Predis;

$redis_config = [
    'host'      =>  '127.0.0.1',
    'port'      =>  6379,
    'database'  =>  15
];
$io = new SocketIO(9999);
$redis = new Predis($redis_config);
#$redis->select('chat_zbing');
$io->on('connection', function($connection)use($io, $redis){
    #$io->emit('connection', 'connection success!');

    $connection->join('zz');

    #连接成功
    $connection->on('login', function($msg)use($io, $connection, $redis){
//        if (!isset($msg['username']) || !isset($msg['password'])) {
//            $connection->emit('login', ['code'=>41, 'msg'=>'login fail']);
//        }

//        if (! isset($msg['uuid'])) return json_encode(['error'=>true, 'msg'=>'login fail']);
//        if ($redis->exists($msg['uuid'])) {
//            if ($userinfo = json_decode($redis->get($msg['uuid']))) {
//                $connection->emit('login', EchoJson(false, 'get success', $userinfo));
//            }
//        }
//        file_put_contents('1.txt', json_encode($msg), FILE_APPEND);
        $msg['user'] == '' ? $msg['user'] = '一个还未起名字的人' : '';
        $io->emit('login', ['msg'=>'欢迎'.$msg['user'].'加入聊天']);
    });

    $connection->on('msg', function($msg)use($io, $redis, $connection){
        //收发消息
        $connection->join($msg['group']);
        $io->to($msg['group'])->emit('msg', $msg);
    });

    $connection->on('info', function($msg)use($io, $redis, $connection){
        //加入会话
        if ($redis->hexists('groups', $msg['group'])) {
            $group = json_decode($redis->hget('groups', $msg['group']), true);
            $group['users'][] = $msg['uuid'];
            $redis->hset('groups', $msg['group'], json_encode($group));
            $connection->join($group);
            $connection->emit('access_group', $group);
        } else {
            $arr = [
                'hourseMan' =>  $msg['uuid'],
                'users' =>  [$msg['uuid']]
            ];
            $redis->hset('groups', $msg['group'], json_encode($arr));
        }
    });
});

function EchoJson($error=true, $msg='', $data=[]) {
    return json_encode(['error'=>$error, 'msg'=>$msg, 'data'=>$data]);
}
Worker::runAll();
